<?php
namespace clt;
class Menutree {
    public $arr = array();
    public $icon = array('│','├','└');
    public $nbsp = "&nbsp;";
    public $ret = '';
    public $level = 0;

    public function __construct($arr=array()) {
        $this->arr = $arr;
        $this->ret = '';
        return is_array($arr);
    }

    public function getchild($pid){
        $a = $newarr = array();
        if(is_array($this->arr)){
            foreach($this->arr as $id => $a){
                if($a['pid'] == $pid) {
					$newarr[$id] = $a;
				}
				
            }
        }
        return $newarr ? $newarr : false;
    }
	
	public function getparent($id){
        $a = $newarr = array();
        if(is_array($this->arr)){
            foreach($this->arr as $id => $a){
                if($a['pid'] == $id) {
					$newarr = $a;
				}
				
            }
        }
        return $newarr ? $newarr : false;
    }
	
   /**
	* 得到树型结构
	* @param int ID，表示获得这个ID下的所有子级
	* @param string 生成树型结构的基本代码，例如："<option value=\$id \$selected>\$spacer\$name</option>"
	* @param int 被选中的ID，比如在做树型下拉框的时候需要用到
	* @return string
	*/
    function get_menu($pid, $str, $sid = 0, $adds = '', $strgroup = ''){
        $number=1;
        $child = $this->getchild($pid);
        if(is_array($child)){
            $total = count($child);
            foreach($child as $id=>$a){
                $j = $k = '';
                if($number == $total){
                    $j .= $this->icon[2];
                }else{
                    $j .= $this->icon[1];
                    $k = $adds ? $this->icon[0] : '';
                }
			    $spacer = $adds ? $adds.$j : '';
                if(empty($a['selected'])){
                    $selected = ($a['id']==$sid) ? 'selected' : '';
                }
                @extract($a);
				
                if($a['module']=="page"){
                    $action='edit';
                    $files = 'id';
                }else{
                    $action='index';
                    $files = 'catid';
                }
				
				$pid == 0 && $strgroup ? eval("\$newstr = \"$strgroup\";") : eval("\$newstr = \"$str\";");
                $this->ret .= $newstr;
                $nbsp = $this->nbsp;
                $this->get_menu($id, $str, $sid, $adds.$k.$nbsp,$strgroup);
                $number++;
				
            }
        }
        return $this->ret;
    }
	
}
?>